package com.zhentao.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.config.AliPayConfig;
import com.zhentao.mapper.ChargeUserMapper;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.pojo.user.ChargeUser;
import com.zhentao.model.pojo.user.pay.RechargeOrder;
import com.zhentao.service.RechargeOrderService;
import com.zhentao.mapper.RechargeOrderMapper;
import com.zhentao.user.ChargeUserThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.zhentao.common.user.UserCommon.RECHARGE_ORDER_LIST;


/**
* @author 31919
* @description 针对表【recharge_order】的数据库操作Service实现
* @createDate 2024-12-30 16:21:00
*/
@Service
public class RechargeOrderServiceImpl extends ServiceImpl<RechargeOrderMapper, RechargeOrder>
    implements RechargeOrderService{

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private AliPayConfig aliPayConfig;
    @Autowired
    private ChargeUserMapper chargeUserMapper;

    // 支付宝沙箱网关地址
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";



    /**
     * @description  用户充值订单列表
     * @author 大毅
     * @date    2024/12/31
     * @return com.zhentao.model.common.dtos.ResponseResult
     */
    @Override
    @Transactional
    public ResponseResult addRechargeOrder(Long total) {
        if (total == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取登录用户
        ChargeUser user = ChargeUserThreadUtils.getChargeUserThreadLocal();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //生产只有数字的uuid
        Long uuid = (long) UUID.randomUUID().toString().replaceAll("-","").hashCode();
        uuid = uuid < 0 ? -uuid : uuid;

        //创建新的充值订单对象
        RechargeOrder rechargeOrder = new RechargeOrder();
        rechargeOrder.setTotal(total);
        rechargeOrder.setUId(user.getId());
        rechargeOrder.setOrderNo(uuid);
        rechargeOrder.setCreateTime(new Date());

        //添加充值订单
        save(rechargeOrder);
        return ResponseResult.okResult(rechargeOrder);
    }

    /**
     * @description  用户充值订单列表
     * @author 大毅
     * @date    2024/12/31
     * @return com.zhentao.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult rechargeOrderList() {
        //        // 获取登录用户
        ChargeUser user = ChargeUserThreadUtils.getChargeUserThreadLocal();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
         //查询该用户的充值订单
            LambdaQueryWrapper<RechargeOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RechargeOrder::getUId, user.getId());
            wrapper.orderByDesc(RechargeOrder::getCreateTime);
            List<RechargeOrder> list = list(wrapper);
            return ResponseResult.okResult(list);
    }
//    @Override
//    public ResponseResult rechargeOrderList() {
//        // 获取登录用户
//        ChargeUser user = ChargeUserThreadUtils.getChargeUserThreadLocal();
//        if (user == null) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
//        }
//        String cacheKey = RECHARGE_ORDER_LIST + user.getId();
//        String orderJson = stringRedisTemplate.opsForValue().get(cacheKey);
//        if (StringUtils.isNotBlank(orderJson)){
//            List<RechargeOrder> list = JSONUtil.toList(orderJson, RechargeOrder.class);
//            return ResponseResult.okResult(list);
//        }
//
//        // 从 MySQL 中查询数据并存入缓存
//        List<RechargeOrder> list = fetchAndCacheRechargeOrders(user.getId(), cacheKey);
//
//
//        return ResponseResult.okResult(list);
//    }
//
//
//
//    private List<RechargeOrder> fetchAndCacheRechargeOrders(Long userId, String cacheKey) {
//        try {
//            // 查询该用户的充值订单
//            LambdaQueryWrapper<RechargeOrder> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(RechargeOrder::getUId, userId);
//            wrapper.orderByDesc(RechargeOrder::getCreateTime);
//            List<RechargeOrder> list = list(wrapper);
//
//            // 将查询结果存入 Redis 缓存
//            String jsonStr = JSONUtil.toJsonStr(list);
//            stringRedisTemplate.opsForValue().set(cacheKey, jsonStr, 30, TimeUnit.MINUTES);
//
//            return list;
//        } catch (Exception e) {
//            // 处理异常情况
//            log.error("Failed to fetch and cache recharge orders for user ID: {}");
//            return Collections.emptyList();
//        }
//    }
}




